package com.myproject.myblogserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myproject.myblogserver.contant.CommonConstants;
import com.myproject.myblogserver.dto.UserLoginDto;
import com.myproject.myblogserver.dto.UserRegisterDto;
import com.myproject.myblogserver.entity.User;
import com.myproject.myblogserver.entity.VerificationCode;
import com.myproject.myblogserver.exception.BusinessException;
import com.myproject.myblogserver.mapper.UserMapper;
import com.myproject.myblogserver.mapper.VerificationCodeMapper;
import com.myproject.myblogserver.service.IUserService;
import com.myproject.myblogserver.utils.BCryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private VerificationCodeMapper verificationCodeMapper;

    @Override
    public User register(UserRegisterDto userRegisterDto) {
        // 查询最新的验证码记录
        var code = verificationCodeMapper.selectOne(
                new LambdaQueryWrapper<VerificationCode>()
                        .eq(VerificationCode::getEmail, userRegisterDto.getEmail()) // 条件：email 匹配
                        .orderByDesc(VerificationCode::getExpireTime) // 按 expireTime 降序排序
                        .last("LIMIT 1"));

        if (code == null) {
            throw new RuntimeException("未找到有效的验证码！");
        }

        // 删除验证码
        verificationCodeMapper.updateIsDeletedByEmail(userRegisterDto.getEmail());

        if (code == null || !code.getCode().equals(userRegisterDto.getVerificationCode())) {
            throw new BusinessException("验证码错误");
        }

        if (code.getExpireTime().isBefore(LocalDateTime.now())) {
            throw new BusinessException("验证码已过期");
        }

        // 创建用户对象并设置属性
        User user = new User();
        user.setName(userRegisterDto.getUsername());
        user.setPassword(BCryptUtil.hashPassword(userRegisterDto.getPassword()));
        user.setEmail(userRegisterDto.getEmail());
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        this.save(user);

        return user;
    }

    @Override
    public User login(UserLoginDto userLoginDto) {
        User user = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getEmail, userLoginDto.getEmail())
                .eq(User::getIsDeleted, CommonConstants.DELETED_STATUS_NO));
        if (user != null)
            return BCryptUtil.checkPassword(userLoginDto.getPassword(), user.getPassword()) ? user : null;

        return user;
    }
}
